package com.cww.study.utils;

import com.alibaba.fastjson.JSON;
import jakarta.xml.bind.DatatypeConverter;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;

/**
 * @program: sbd
 * @description: 参数工具类
 * @author: 陈英俊
 * @create: 2022-01-24 09:50
 */
public class ParameterUtils {
    private ParameterUtils() {
    }

    /**
     * 将参数里面的不必要参数去除,然后将参数md5加密
     *
     * @param requestJSON 请求转成的json
     * @param excludeKeys 不需要加密的参数
     * @return
     */
    public static String paramMD5( String requestJSON, String... excludeKeys) {
        TreeMap<String,String> paramTreeMap = JSON.parseObject(requestJSON, TreeMap.class);
        if (excludeKeys!=null) {
            List<String> ignoreKeys = Arrays.asList(excludeKeys);
            if (!ignoreKeys.isEmpty()) {
                for (Object ignoreKey : ignoreKeys) {
                    paramTreeMap.remove(ignoreKey);
                }
            }
        }
        String paramTreeMapJSON = JSON.toJSONString(paramTreeMap);
        return doParamMD5(paramTreeMapJSON);
    }

    /**
     * 将去除之后的参数进行md5加密
     * @param src
     * @return
     */
    private static String doParamMD5(String src) {
        String res = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] mdBytes = messageDigest.digest(src.getBytes());
            res = DatatypeConverter.printHexBinary(mdBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
}
